<?php

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;

class Recovery extends Command
{
    private $start_date = '';
    private $end_date = '';

    protected function configure()
    {
        $this->setName('recovery')
            ->addArgument('action', Argument::OPTIONAL, "方法名称")
            ->addOption('role', null, Option::VALUE_REQUIRED, '角色名称')
            ->addOption('start_date', null, Option::VALUE_REQUIRED, '开始日期')
            ->addOption('end_date', null, Option::VALUE_REQUIRED, '结束日期')
            ->setDescription('回收分析');
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        if (method_exists($this, $action)) {
            $role = $input->getOption('role') ?? 'agent';
            $start_date = $input->hasOption('start_date') ? $input->getOption('start_date') : date('Y-m-d');
            $end_date = $input->hasOption('end_date') ? $input->getOption('end_date') : date('Y-m-d');
            if ($action == 'runToday' || $action == 'runYesterday') {
                $this->$action($role);
            } elseif ($action == 'rerunHistory') {
                $this->$action($role, $start_date, $end_date);
            } else {
                $this->$action();
            }
        }
    }


    /**
     * 更新历史数据
     * @param $role
     * @param $start_date
     * @param $end_date
     */
    private function rerunHistory($role, $start_date, $end_date)
    {
        $dates = getDateByRange($start_date, $end_date);
        foreach ($dates as $k => $date) {
            $this->runDaily($date, $role);
        }
    }

    /**
     * 更新当日数据
     * @param $role
     */
    private function runToday($role)
    {
        $today = date("Y-m-d");
        $this->runDaily($today, $role);
    }

    /**
     * 更新昨日数据
     * @param $role
     */
    public function runYesterday($role)
    {
        $today = date("Y-m-d", strtotime("-1 day"));
        $this->runDaily($today, $role);
    }


    private function runDaily($detailDate, $role)
    {
        if ($role == 'channel') {
            $table = "rp_recovery_channel";
            $tableDetail = "rp_recovery_channel_detail";
        } else {
            $table = "rp_recovery_agent";
            $tableDetail = "rp_recovery_agent_detail";
        }
        $staterDate = date("Y-m-d", strtotime($detailDate . ' -29 days'));
        $roleId = Db::table('cms_manager_role')->where('alias', $role)->value('id');
        $accounts = Db::table('cms_manager_user')->field("id,create_time")->where('role_id', $roleId)->order("id desc")->select();
        $dates = getDateByRange($staterDate, $detailDate);

        foreach ($dates as $k => $rpDate) {
            foreach ($accounts as $account) {
                $regDate = date("Y-m-d", strtotime($account['create_time']));
                if ($rpDate >= $regDate) {
                    /**
                     * 数据日期大于等于注册才需要跑任务
                     */
                    $pWhere = [];
                    $pWhere['rp_date'] = $rpDate;
                    $pWhere['uid'] = $account['id'];
                    if ($rpDate == $detailDate) {
                        /**
                         * 更新当天数据
                         */
                        $pid = Db::table($table)->where($pWhere)->value('id');
                        $data = $this->getDayData($rpDate, $account['id'], $role);
                        if ($pid) {
                            Db::table($table)->where("id", $pid)->update($data);
                        } else {
                            Db::table($table)->where($pWhere)->insert($data);
                        }
                        echo "{$account['id']}_源：{$rpDate}_日：{$detailDate}_父级更新成功" . PHP_EOL;
                    }
                    $data = $this->getDayDataDetail($rpDate, $detailDate, $account['id'], $role);
                    /**
                     * 大于0再更新数据，节省点执行的sql语句，表里明细记录也能少好多
                     */
                    if ($data['money'] > 0){
                        /**
                         * 更新明细
                         */
                        $dWhere = [];
                        $dWhere['rp_date'] = $rpDate;
                        $dWhere['uid'] = $account['id'];
                        $dWhere['date'] = $detailDate;
                        $id = Db::table($tableDetail)->where($dWhere)->value('id');
                        if ($id) {
                            Db::table($tableDetail)->where("id", $id)->update($data);
                        } else {
                            Db::table($tableDetail)->insert($data);
                        }
                        $sumDetail = Db::table($tableDetail)->field("sum(money) money,sum(fast_money) fast_money,sum(nu_money) nu_money")->where("rp_date", $rpDate)->where('uid', $account['id'])->find();
                        if ($sumDetail) {
                            Db::table($table)->where($pWhere)->update($sumDetail);
                        }
                        echo "{$account['id']}_源：{$rpDate}_日：{$detailDate}_明细更新成功" . PHP_EOL;
                    }
                } else {
                    echo "{$account['id']}_{$rpDate}_忽略" . PHP_EOL;
                    continue;
                }
            }
        }
    }


    /**
     * 获取某日期数据
     * @param $date
     * @param $aid
     * @param $role
     * @return mixed
     */
    private function getDayData($date, $aid, $role)
    {
        if ($role == 'channel') {
            $fromField = "channel_id";
            $userFromField = "source_channel_id";
        } else {
            $fromField = "agent_id";
            $userFromField = "source_agent_id";
        }
        $data['rp_date'] = $date;
        $data['uid'] = $aid;
        $data['nu_num'] = Db::table('quick_user')->where($userFromField, $aid)->where("regdate", $date)->count();
        $data['cu_num'] = Db::table('quick_user_change_log')->field("uid")->where($fromField, $aid)->where("change_date", $date)->group("uid")->count();
        $data['adu_num'] = Db::table("quick_user_add_shortcut")->where("create_date",$date)->where($fromField,$aid)->count();
        return $data;
    }


    /**
     * 获取某日期明细数据
     * @param $rpDate
     * @param $date
     * @param $aid
     * @param $role
     * @return mixed
     */
    private function getDayDataDetail($rpDate, $date, $aid, $role)
    {
        if ($role == 'channel') {
            $fromField = "channel_id";
        } else {
            $fromField = "agent_id";
        }
        $data['rp_date'] = $rpDate;
        $data['uid'] = $aid;
        $diff = strtotime($date) - strtotime($rpDate);
        $data['t_index'] = ($diff / 86400) + 1;//下标从1开始
        $data['date'] = $date;
        $data['money'] = Db::table("pay_order_success")->where($fromField, $aid)->where("user_source_date", $rpDate)->where("create_date", $date)->sum('total_fee') ?? 0;
        if ($rpDate >= '2024-05-15'){
            $data['fast_money'] = Db::table("pay_order_success")->where($fromField, $aid)->where("user_source_date", $rpDate)->where("create_date", $date)->where("recharge_times", 1)->sum('total_fee') ?? 0;
            $data['nu_money'] = Db::table("pay_order_success")->where($fromField, $aid)->where("user_reg_date", $rpDate)->where("create_date", $date)->sum('total_fee') ?? 0;
        }else{
            $data['fast_money'] = 0;
            $data['nu_money'] = 0;
        }
        return $data;
    }
}